import json
import logging
import random
import aiohttp
import aioredis
import lxml.html
import time

from PIL import Image
from faker import Faker
import asyncio
import base64

from io import BytesIO
from pyzbar.pyzbar import decode
# from .cmcc_10086 import get_code2, report_err_code

logger = logging.getLogger("cmcc")


async def get_code(content):
    headers = {"Authorization": "APPCODE 370107e384e1409b9af32352c20e6100"}
    data = {
        'v_pic': base64.b64encode(content).decode(),
        'v_type': 'ne4'
    }
    print(data)
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'http://yzm.cqjianjiao.com/yzm'
        async with session.post(url, data=data) as rsp:
            rsp_obj = await rsp.text()
            print('----')
            print(rsp_obj)
            rsp_obj = json.loads(rsp_obj)
            if rsp_obj['errCode'] == 0:
                return rsp_obj['v_code']
            else:
                print(rsp_obj)
            return None


async def myget_code(content):
    # files = {'image_file': ('test', content, 'img/jpeg')}
    data = aiohttp.FormData()
    data.add_field('image_file',
                   content,
                   filename='test',
                   content_type='img/jpeg')
    async with aiohttp.ClientSession() as session:
        url = 'http://134.175.9.163:8080/b'
        async with session.post(url, data=data) as rsp:
            data = await rsp.json()
            logger.info(data)
            return data['value']


async def get_aliqr(usertel, amount, cookies, conn_redis):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        'Cookie': cookies,
    }

    proxys = await conn_redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info("代理%s|%s", usertel, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        for _ in range(10):
            async with session.get('http://189.cn/login/index.do', proxy=conn) as rsp:
                login_info = await rsp.json()
                logger.info(login_info)
                nickname = login_info['dataObject'].get('nickName')
                if not nickname:
                    return {'code': 4, 'message': '登录失效'}
                    # return {'cocde': login_info['code'], "message": login_info['errorDescription']}

            async with session.get('http://189.cn/chongzhi', proxy=conn) as rsp:
                pass
            async with session.get('http://189.cn/trade/pay/directcharge/bank.do?_=1559805821592', proxy=conn) as rsp:
                pass
            nostr = str(time.time()).replace('.', '')[:13]
            imageurl = 'http://189.cn/portal/captcha/aircz.do?date=' + nostr
            headers.update({'Referer': 'http://189.cn/chongzhi/',
                            'Host': 'http://189.cn/',
                            'X-Requested-With': 'XMLHttpRequest',
                            'Host': '189.cn'})
            async with session.get(imageurl, proxy=conn) as rsp:
                img_content = await rsp.read()
                # captcha = await get_code2(img_content)
                captcha = await myget_code(img_content)

                if len(captcha) != 4:
                    # await report_err_code(img_content)
                    with open('/app/log/captcha3/%s_%s.png' % (captcha, int(time.time())), 'wb') as f:
                        f.write(img_content)

                    continue
                # image.show()
                # captcha = input()
                # print(captcha)
                data = {'accountNumber': usertel,
                        'checkPassCode': captcha,
                        'payAmount': amount,
                        'shopId': 10036,
                        'sp': 1,
                        'attributes[0][isTogetherRecharge]': '0'}
            async with session.post('http://189.cn/trade/recharge/captcha/type.do', data={"phone": usertel}) as rsp:
                text = await rsp.text()
            order_url = 'http://189.cn/trade/recharge/bank.do'
            async with session.post(order_url, data=data, proxy=conn, headers=headers) as rsp:
                text = await rsp.text()
                rsp_obj = await rsp.json()
                # rsp_obj = json.loads(rsp.content.decode())
                logger.info(rsp_obj)
            # {'code': 'BE1016', 'dataObject': None, 'errorDescription': '验证码输入有误'}

            if rsp_obj['code'] == '0':
                orderId = rsp_obj['dataObject']['orderId']
                qrcode_url = 'http://189.cn/trade/payment/wechat.do?orderId=%s&paymentCode=114&t=%s' % (orderId, nostr)
                _, message = await ctcc_query(orderId, cookies, conn_redis)
                logger.info("下单检测|%s|%s", usertel, message)
                if message == "未找到订单":
                    return {"code": 1, 'message': '未关联到账号'}
                for _ in range(3):
                    async with session.get(qrcode_url, headers=headers, proxy=conn) as resp:
                        content = await resp.read()
                        if not content:
                            continue
                        # logger.info(content)
                        decode_result = decode(Image.open(BytesIO(content)))
                        logger.info(decode_result[0].data)
                        # logger.info(decode_result[0].data)
                        qrcode = decode_result[0].data.decode()
                        logger.info(qrcode)
                        # with open('/app/log/captcha3/%s_%s.png' % (captcha, int(time.time())), 'wb') as f:
                        #     f.write(img_content)
                        return {'code': 0, 'message': rsp_obj['errorDescription'], 'qrcode': qrcode, "orderid": orderId}
            else:
                if rsp_obj['code'] == 'BE1016':
                    with open('/app/log/err_captcha3/%s_%s.png' % (captcha, int(time.time())), 'wb') as f:
                        f.write(img_content)
                    continue
                # else:
                #     with open('/app/log/captcha3/%s_%s.png' % (captcha, int(time.time())), 'wb') as f:
                #         f.write(img_content)
                return {'code': rsp_obj['code'], 'message': rsp_obj['errorDescription']}


async def ctcc_query(order_id, cookies, conn_redis):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        'CLIENT-IP': ip,
        'X-FORWARDED-FOR': ip,
        'Cookie': cookies
    }

    proxys = await conn_redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info("代理%s|%s", order_id, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    logger.info(conn)

    url = 'http://www.189.cn/dqmh/userCenter/myOrderInfoList.do'
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get('http://www.189.cn/login/index.do', proxy=conn) as rsp:
            login_info = await rsp.json()
            logger.info(login_info)
            nickname = login_info['dataObject'].get('nickName')
            if not nickname:
                return '9', '登录失效'
        for i in range(1, 35):
            data = {
                'method': 'listMyOrderInfo_new',
                'date_area': '',
                'status_type': '',
                'order_type': 'orders_recharge',
                'pageNo': i,
                'isVs': 'no'
            }
            async with session.get(url, params=data, proxy=conn) as rsp:
                text = await rsp.text()
                root = lxml.html.fromstring(text)
                links = root.xpath("//a[text()='订单详情']")
                for a in links:
                    if order_id in a.attrib['href']:
                        result = a.getparent().getprevious().text
                        if "等待支付" in result:
                            orderstate = '8'
                            message = '等待支付'
                        elif "充值成功" in result:
                            orderstate = '0'
                            message = '充值成功'
                        elif "失效订单" in result:
                            orderstate = '1'
                            message = '失效订单'
                        elif '订单关闭' in result:
                            orderstate = '1'
                            message = '订单关闭'
                        elif '支付中' in result:
                            orderstate = '8'
                            message = '支付中'
                        elif '退款成功' in result:
                            orderstate = '1'
                            message = '退款成功'
                        else:
                            orderstate = '9'
                            message = result.strip()
                        return orderstate, message

        return '9', '未找到订单'


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    # print(get_aliqr('18122730927', '10'))
    # print(loop.run_until_complete(get_aliqr('18122730927', '10')))
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    # print(loop.run_until_complete(query('1000000083420190311221832079', cookies, redis)))
    cookies ='i_vnum=19; ijg=1554690014103; svid=4550787D3ADEDAC9; s_fid=6DA83A8D4C371558-130A4FADA007974C; lvid=22ae45eee43f4537312e53d6c60b2c19; nvid=1; trkId=9D554181-E4C5-4EF2-8B3D-9FCB8B96727A; JSESSIONID-JT=82D5334D354903BECDD2F88187C10677-n3; s_cc=true; aactgsh111220=8393653790; userId=309%7C20170100000085436643; isLogin=logined; .ybtj.189.cn=B5A0D1FA5AD2F9F4E53E547991264637; cityCode=bj; flag=2; SHOPID_COOKIEID=10001; loginStatus=logined; s_sq=eshipeship-189-all%3D%2526pid%253D%25252Fchongzhi%25252F%2526pidt%253D1%2526oid%253Dhttp%25253A%25252F%25252F189.cn%25252Fchongzhi%25252Fimages%25252F12.jpg%2526ot%253DIMAGE; trkHmClickCoords=495%2C1055%2C2105' 
    print(loop.run_until_complete(get_aliqr('18122730927', '50', cookies, redis)))
    loop.close()
    # print(query('1000000083420181001602639114'))
